﻿package com.farm.bpm.web.action;

import com.farm.authority.service.UserServiceInter;
import com.farm.bpm.form.Form;
import com.farm.bpm.server.FarmBpmServiceInter;

import com.farm.web.easyui.EasyUiUtils;

import java.io.File;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.activiti.engine.task.Task;
import org.apache.log4j.Logger;

import com.farm.core.page.CommitType;
import com.farm.core.page.PageSet;
import com.farm.core.page.PageType;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.result.DataResult;
import com.farm.doc.domain.FarmDocfile;
import com.farm.doc.server.FarmFileManagerInter;
import com.farm.doc.server.FarmFileManagerInter.FILE_TYPE;
import com.farm.web.WebSupport;
import com.farm.web.spring.BeanFactory;

/**
 * 用户任务
 * 
 * @author autoCode
 * 
 */
public class ActionActRuTaskQuery extends WebSupport {
	private Map<String, Object> jsonResult;// 结果集合
	private DataQuery query;// 条件查询
	private PageSet pageset;// 请求状态
	private String ids;// 主键集合
	private Map<String, List<Map<String, Object>>> prodefs;// 可以启动的流程集合
	private Form form;
	private String executionId;
	private Map<String, String> fields;// 表单
	private String taskFileFileName;
	private String taskFileContentType;
	private File taskFile;
	private int error;
	private String url;
	private String message;
	private InputStream inputStream;
	private String id;
	private boolean onlyone = false;
	private boolean haveCandidate = false;
	private final static UserServiceInter userIMP = (UserServiceInter) BeanFactory
			.getBean("farm_authority_user_ProxyId");

	/**
	 * 上传文件
	 * 
	 * @return
	 */
	public String upload() {
		try {
			String fileid = null;
			fileid = fileIMP.saveFile(taskFile, FILE_TYPE.HTML_INNER_IMG,
					taskFileFileName, getCurrentUser());
			error = 0;
			url = fileIMP.getFileURL(fileid);
			message = "";
			id = fileid;
		} catch (Exception e) {
			error = 1;
			message = e.getMessage();
		}
		return SUCCESS;
	}

	/**
	 * 附件下载
	 * 
	 * @return
	 */
	public String download() {
		try {
			FarmDocfile file = fileIMP.getFile(id);
			inputStream = file.getInputStream();
			taskFileFileName = file.getName();
			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.DEL,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 查询正在办理任务
	 * 
	 * @return
	 */
	public String queryall() {
		try {
			query = EasyUiUtils.formatGridQuery(getRequest(), query);
			DataResult result = aloneIMP.queryUserCurrentTask(getCurrentUser(),
					userIMP.getUserPostIds(getCurrentUser().getId()));
			jsonResult = EasyUiUtils.formatGridData(result);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return SUCCESS;
	}

	/**
	 * 查询当前用户参与的流程
	 * 
	 * @return
	 */
	public String queryJoined() {
		try {
			query = EasyUiUtils.formatGridQuery(getRequest(), query);
			DataResult result = aloneIMP.queryUserJoinTask(getCurrentUser());
			jsonResult = EasyUiUtils.formatGridData(result);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return SUCCESS;
	}

	@Override
	public void addActionError(String anErrorMessage) {
		// 这里要先判断一下，是我们要替换的错误，才处理
		if (anErrorMessage
				.startsWith("Request exceeded allowed size limit! Max size allowed is")) {
			Pattern pattern = Pattern.compile("[,|\\d]+");
			Matcher m = pattern.matcher(anErrorMessage);
			// 匹配一次
			m.find();
			String s1 = m.group().replaceAll(",", "");// 上传的文件大小
			// 再匹配一次
			m.find();
			String s2 = m.group().replaceAll(",", "");// 所限制的大小
			String fileUploadErrorMessage = null;
			if (!s1.equals("") && !s2.equals("")) {
				fileUploadErrorMessage = "你上传的文件大小（" + Long.valueOf(s2) / 1024
						/ 1024 + "M）超过允许的大小（" + Long.valueOf(s1) / 1024 / 1024
						+ "M）";
				getRequest().setAttribute("fileUploadErrorMessage",
						fileUploadErrorMessage);
				// 将信息替换掉
				super.addActionError(fileUploadErrorMessage);
			}
		} else {// 否则按原来的方法处理
			super.addActionError(anErrorMessage);
		}
	}

	/**
	 * 查询等待办理任务
	 * 
	 * @return
	 */
	public String queryallwaitTask() {
		try {
			query = EasyUiUtils.formatGridQuery(getRequest(), query);
			DataResult result = aloneIMP.queryUserWaitingTask(getCurrentUser(),
					userIMP.getUserPostIds(getCurrentUser().getId()));
			jsonResult = EasyUiUtils.formatGridData(result);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return SUCCESS;
	}

	/**
	 * 启动任务流程
	 * 
	 * @return
	 */
	public String startProcess() {
		try {
			aloneIMP.startProcessDef(ids, getCurrentUser(), userIMP
					.getUserPostIds(getCurrentUser().getId()));
			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.DEL,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 认领任务
	 * 
	 * @return
	 */
	public String claim() {
		try {
			for (String id : parseIds(ids)) {
				aloneIMP.claimTask(id, getCurrentUser());
			}
			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.DEL,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 放弃认领任务
	 * 
	 * @return
	 */
	public String unclaim() {
		try {
			aloneIMP.unclaimTask(ids);
			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.DEL,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 委托办理任务
	 * 
	 * @return
	 */
	public String setAssignee() {
		try {
			aloneIMP.setAssignee(ids, id);
			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.DEL,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 进入任务页面
	 * 
	 * @return
	 */
	public String forwordTaskPage() {
		loadUserstartProcessDef();
		return SUCCESS;
	}

	/**
	 * 修改任务表单
	 * 
	 * @return
	 */
	public String editSubmit() {
		try {
			aloneIMP.saveTaskFormData(ids, fields);
			pageset = new PageSet(PageType.UPDATE, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.UPDATE,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 完成提交任务
	 * 
	 * @return
	 */
	public String compeletSubmit() {
		try {
			aloneIMP.saveTaskFormData(ids, fields);
			aloneIMP.submitTask(ids);
			pageset = new PageSet(PageType.UPDATE, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.UPDATE,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 加载用户当前可启动流程
	 */
	private void loadUserstartProcessDef() {
		try {
			prodefs = aloneIMP.getUserStartableProcessDef(getCurrentUser(),
					userIMP.getUserPostIds(getCurrentUser().getId()));
		} catch (SQLException e) {
			log.error("获取用户流程失败" + e + e.getMessage());
		}
		log.info("当前用户可以启动的流程条数：" + prodefs.size());
	}

	/**
	 * 跳转
	 * 
	 * @return
	 */
	public String forSend() {
		// TODO 自动生成代码,修改后请去除本注释
		return SUCCESS;
	}

	/**
	 * 显示详细信息（修改或浏览时）
	 * 
	 * @return
	 */
	public String view() {
		return SUCCESS;
	}

	/**
	 * 处理任务
	 * 
	 * @return
	 */
	public String doTask() {
		form = aloneIMP.getTaskForm(ids);
		Task task = aloneIMP.getTask(ids);
		// 流程参与人
		if (aloneIMP.queryProcessInstanceIdentityLinks(query,
				task.getProcessInstanceId()).getResultList().size() == 1) {
			onlyone = true;
		} else {
			onlyone = false;
		}
		// 候选人
		haveCandidate = false;
		for (Map<String, Object> node : aloneIMP.queryTaskIdentityLinks(query,
				task.getId()).getResultList()) {
			if (node.get("TYPE").equals("candidate")) {
				haveCandidate = true;
			}
		}
		executionId = task.getProcessInstanceId();
		return SUCCESS;
	}

	private final static FarmBpmServiceInter aloneIMP = (FarmBpmServiceInter) BeanFactory
			.getBean("farmBpmProxyId");
	private final static FarmFileManagerInter fileIMP = (FarmFileManagerInter) BeanFactory
			.getBean("farm_docFileProxyId");

	// ----------------------------------------------------------------------------------
	public DataQuery getQuery() {
		return query;
	}

	public void setQuery(DataQuery query) {
		this.query = query;
	}

	public PageSet getPageset() {
		return pageset;
	}

	public void setPageset(PageSet pageset) {
		this.pageset = pageset;
	}

	public boolean isHaveCandidate() {
		return haveCandidate;
	}

	public void setHaveCandidate(boolean haveCandidate) {
		this.haveCandidate = haveCandidate;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public Map<String, Object> getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(Map<String, Object> jsonResult) {
		this.jsonResult = jsonResult;
	}

	public Map<String, List<Map<String, Object>>> getProdefs() {
		return prodefs;
	}

	public void setProdefs(Map<String, List<Map<String, Object>>> prodefs) {
		this.prodefs = prodefs;
	}

	public Form getForm() {
		return form;
	}

	public void setForm(Form form) {
		this.form = form;
	}

	public String getExecutionId() {
		return executionId;
	}

	public void setExecutionId(String executionId) {
		this.executionId = executionId;
	}

	public Map<String, String> getFields() {
		return fields;
	}

	public void setFields(Map<String, String> fields) {
		this.fields = fields;
	}

	public String getTaskFileFileName() {
		return taskFileFileName;
	}

	public void setTaskFileFileName(String taskFileFileName) {
		this.taskFileFileName = taskFileFileName;
	}

	public String getTaskFileContentType() {
		return taskFileContentType;
	}

	public void setTaskFileContentType(String taskFileContentType) {
		this.taskFileContentType = taskFileContentType;
	}

	public File getTaskFile() {
		return taskFile;
	}

	public void setTaskFile(File taskFile) {
		this.taskFile = taskFile;
	}

	public int getError() {
		return error;
	}

	public void setError(int error) {
		this.error = error;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public boolean isOnlyone() {
		return onlyone;
	}

	public void setOnlyone(boolean onlyone) {
		this.onlyone = onlyone;
	}

	private static final Logger log = Logger
			.getLogger(ActionActRuTaskQuery.class);
	private static final long serialVersionUID = 1L;
	/**
	 * 加载树节点 public String loadTreeNode() { treeNodes =
	 * EasyUiTreeNode.formatAjaxTree(EasyUiTreeNode .queryTreeNodeOne(id,
	 * "SORT", "alone_menu", "ID", "PARENTID", "NAME").getResultList(),
	 * EasyUiTreeNode .queryTreeNodeTow(id, "SORT", "alone_menu", "ID",
	 * "PARENTID", "NAME").getResultList(), "PARENTID", "ID", "NAME"); return
	 * SUCCESS; }
	 * 
	 * @return
	 */
}
